using System.Reflection;
using BuildingBlocks.Abstractions.Permissions;
using BuildingBlocks.Infrastructure.EventBus;
using Catalog.Application.Contracts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Catalog.Infrastructure.HostedService;

public class CatalogStartupTasks : IHostedService
{
    private readonly IEventBus _eventBus;
    private readonly IPermissionProvider _provider;
    private readonly IRedisService _redis; // 你可以封装 StackExchange.Redis

     private readonly IPermissionBindingServiceClient _permissionbindingClient;
    public CatalogStartupTasks(IEventBus eventBus, IPermissionProvider provider, IRedisService redis, IPermissionBindingServiceClient permissionbindingClient)
    {
        _eventBus = eventBus;
        _provider = provider;
 
        _permissionbindingClient = permissionbindingClient;  
        _redis = redis;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        // 扫描权限
        var permissions = _provider.GetPermissions().ToList();

        // 发布事件
        var evt = new PermissionRegisteredEvent("CatalogService", permissions);
        await _eventBus.PublishAsync(evt);


        // 请求权限中心 API，获取绑定关系表
        var bindings = await _permissionbindingClient.GetBindingsAsync("CatalogService");

        // 写入 Redis 缓存
        // Key 可以设计成 Permission:CatalogService
        var cacheKey = $"Permission:CatalogService"; 
        await _redis.SetAsync(cacheKey, bindings, TimeSpan.FromHours(1));
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}